<?php declare(strict_types=1);
/**
 * This file is part of Swoft.
 *
 * @link https://swoft.org
 * @document https://swoft.org/docs
 * @contact group@swoft.org
 * @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Http\Controller\Admin;

use App\Exception\HttpException;
use App\Model\Logic\LoginLogic;
use Swoft\Bean\Annotation\Mapping\Inject;
use Swoft\Http\Message\Request;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\Middleware;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\Http\Server\Annotation\Mapping\RequestMethod;
use Swoft\Http\Session\HttpSession;
use Swoft\Validator\Annotation\Mapping\Validate;
use Swoft\Validator\Annotation\Mapping\ValidateType;
use App\Http\Middleware\CheckLoginMiddleware;

/**
 * Class LoginController
 *
 * @Controller(prefix="/admin")
 * @package App\Http\Controller\Admin
 */
class LoginController{

    /**
     * @Inject()
     * @var LoginLogic
     */
    private $loginLogic;
    /**
     * 加载登录页
     * @RequestMapping(route="login", method=RequestMethod::GET)
     * @Validate(validator="LoginValidator",type=ValidateType::GET)
     * @return array
     * @throws \Throwable
     */
    public function index()
    {
//        // 设置值
//        HttpSession::current()->set(string $key, $value): viod
//        // 获取值
//        HttpSession::current()->get(string $key, $default): viod
//        // 检查是否存在
//        HttpSession::current()->has(string $key): bool
//        // 删除值
//        HttpSession::current()->delete(string $key): bool
        return view('admin/login/login');
    }

    /**
     * 加载登录页
     * @RequestMapping(route="dologin", method=RequestMethod::POST)
     * @return array
     * @throws HttpException
     */
    public function login(Request $request)
    {
        if (!$request->isAjax()){
            throw new HttpException('请求失败',1);
        }
        $data = $request->post();
        // 登录验证
        $this->loginLogic->checkLogin($data);
//        return password_hash('111111',PASSWORD_DEFAULT); // 生成密码
//        password_verify($result['password'], $data['password'])
    }

    /**
     * @RequestMapping(route="logout", method={RequestMethod::GET})
     * @Middleware(CheckLoginMiddleware::class)
     * @param Request $request
     * @throws HttpException
     */
    public function logout(Request $request){
        if (!$request->isAjax()){
            throw new HttpException('请求失败',1);
        }
        if (HttpSession::current()->delete('userid') &&
        HttpSession::current()->delete('username')){
            throw new HttpException('已经安全退出',0);
        }
    }
}
